"""LeadIntention repository for database operations."""

from __future__ import annotations

from typing import TYPE_CHECKING

from sqlalchemy import select
from sqlalchemy.orm import Session

from ..models.lead_intention import LeadIntention
from ..schemas.lead_intention import LeadIntentionCreate, LeadIntentionUpdate
from .base import BaseRepository

if TYPE_CHECKING:
    from ..models.lead_intention import LeadIntention as LeadIntentionModel


class LeadIntentionRepository(BaseRepository[LeadIntention, LeadIntentionCreate, LeadIntentionUpdate]):
    """LeadIntention repository for CRUD operations."""

    def __init__(self, db: Session):
        """Initialize repository with database session."""
        super().__init__(LeadIntention, db)

    def get_by_lead_id(self, lead_id: int) -> list[LeadIntentionModel]:
        """
        获取某个客户的所有意向（按优先级排序）.

        Args:
            lead_id: 客户ID

        Returns:
            该客户的所有额外意向列表
        """
        stmt = (
            select(LeadIntention)
            .where(LeadIntention.lead_id == lead_id)
            .order_by(LeadIntention.priority.asc())
        )
        result = self.db.execute(stmt)
        return list(result.scalars().all())

    def get_primary_intention(self, lead_id: int) -> LeadIntentionModel | None:
        """
        获取客户的第一个意向（优先级最高）.

        Args:
            lead_id: 客户ID

        Returns:
            优先级最高的意向，如果没有则返回 None
        """
        stmt = (
            select(LeadIntention)
            .where(LeadIntention.lead_id == lead_id)
            .order_by(LeadIntention.priority.asc())
            .limit(1)
        )
        result = self.db.execute(stmt)
        return result.scalar_one_or_none()

    def create_batch(self, intentions: list[LeadIntentionCreate]) -> list[LeadIntentionModel]:
        """
        批量创建多个意向.

        Args:
            intentions: 意向创建对象列表

        Returns:
            创建的意向对象列表
        """
        db_objs = [LeadIntention(**intention.model_dump()) for intention in intentions]
        self.db.add_all(db_objs)
        self.db.flush()
        return db_objs

    def delete_by_lead_id(self, lead_id: int) -> int:
        """
        删除某个客户的所有意向.

        Args:
            lead_id: 客户ID

        Returns:
            删除的记录数
        """
        stmt = select(LeadIntention).where(LeadIntention.lead_id == lead_id)
        result = self.db.execute(stmt)
        intentions = result.scalars().all()

        count = len(intentions)
        for intention in intentions:
            self.db.delete(intention)
        self.db.flush()

        return count

    def update_priority_batch(self, updates: list[tuple[int, int]]) -> None:
        """
        批量更新意向优先级.

        Args:
            updates: [(intention_id, new_priority), ...] 元组列表
        """
        for intention_id, new_priority in updates:
            intention = self.get(intention_id)
            if intention:
                intention.priority = new_priority
        self.db.flush()
